package cannot.controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import cannot.pojo.User;
import cannot.pojo.UserDetail;
import cannot.service.UserDetailService;
import cannot.service.UserService;
import cannot.shiro.ShiroUtil;
import cannot.util.FileUtil;
import cannot.util.ImageUtil;
import cannot.util.StoragePlace;

@Controller
public class UserController {
	String imgPath =StoragePlace.basicPlace+"userheadimg"+File.separator;
	@Autowired
	UserDetailService userDetailService;
	@Autowired
	UserService userService;
	/**
	 * 添加用户头像
	 * @param picture
	 * @return
	 */
	@RequestMapping(method = RequestMethod.POST, path = "/user_headimage_upload")
	@ResponseBody
    public String uploadPicture(HttpServletRequest req,@RequestPart("file") MultipartFile picture) {
    	  String pictureName = UUID.randomUUID().toString() + ".jpg";
          try {
              File file = new File(imgPath);
              file.mkdirs();
              File f = new File(imgPath+ pictureName);
              picture.transferTo(f);
              ImageUtil.resizeImage(f, 180, 180, f);
          } catch (Exception e) {
          }
          return pictureName;
    }
	
	/**
	 * 获取用户头像
	 */
	@RequestMapping("user_headimage_load")
	public void renderPicture(String pictureId, HttpServletResponse response) {
    String path =imgPath+ pictureId;
    try {
        byte[] bytes = FileUtil.toByteArray(path);
        response.getOutputStream().write(bytes);
    }catch (Exception e){
        //如果找不到图片就返回一个默认图片
        try {
            response.sendRedirect("img/login-icon.png");
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }
	}
	
	/**
	 * 修改用户信息，修改完后更新session中用户信息
	 */
	@RequestMapping("user_acount_add")
	@ResponseBody
	public String userAcountAdd(UserDetail userDetail,HttpSession session){
		User u = (User) session.getAttribute("user");
		userDetailService.updateUserDetail(userDetail);
		u.setUserDetail(userDetail);
		return "SUCCESS";
	}
	/**
	 * 账号设置的跳转
	 */
	@RequestMapping("usercenter_useraccount")
	public String userCenterAccount(){
		return "usercenter/rightContent/userAccount";
	}
}
